﻿using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Controllers;
using System.Reflection;

namespace RemoteSensingImageDirectServer.Register.API
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public partial class HiddenApiAttribute : Attribute { }
    public class HiddenApiFilter : IDocumentFilter
    {
        /// <summary> 
        /// 重写Apply方法，移除隐藏接口的生成 
        /// </summary> 
        /// <param name="swaggerDoc">swagger文档文件</param> 
        /// <param name="schemaRegistry"></param> 
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            foreach (ApiDescription apiDescription in context.ApiDescriptions)
            {
                // 获取动作描述器
                var actionDescriptor = apiDescription.ActionDescriptor;

                if (apiDescription.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
                {
                    // 检查控制器特性
                    var controllerAttributes = controllerActionDescriptor.ControllerTypeInfo.GetCustomAttributes(typeof(HiddenApiAttribute), true);

                    // 检查动作特性
                    var actionAttributes = controllerActionDescriptor.MethodInfo.GetCustomAttributes(typeof(HiddenApiAttribute), true);

                    if (controllerAttributes.Length > 0 && actionAttributes.Length > 0)
                    {
                        continue;
                    }
                }
                    
                var key = "/" + apiDescription.RelativePath.TrimEnd('/');
                if (swaggerDoc.Paths.ContainsKey(key))
                    swaggerDoc.Paths.Remove(key);
            }
        }

    }
}
